/* *
 * @program: LivePublisher
 *
 * @description: ${description}
 *
 * @author: 909845
 *
 * @create: 2019-03-28 15:50
***/

#include "LivePublisher.h"

#define TAG "MID[m_strManagerID][" << m_strStreamID << "]- "

CLivePublisher::CLivePublisher(const char* pManagerID, const char *pStreamID, const char *pHost, const char *pUri, const shared_ptr<CEventEngine> &spEngine):
        m_strManagerID(pManagerID),
        m_strStreamID(pStreamID),
        m_strHost(pHost),
        m_strUri(pUri),
        m_spEngine(spEngine)
{
    TRACE_LOG(TAG << "Create CLivePublisher");
}

CLivePublisher::~CLivePublisher()
{
    TRACE_LOG(TAG << "Destroy ~CLivePublisher");
}

bool CLivePublisher::Initialize(bool bRecord)
{
    bool bRet = false;
    do
    {
        Assert(m_spThis != nullptr);
        m_spMsgHandler = shared_ptr<CMyTimer>(new CMyTimer(m_spEngine));
        m_spMsgHandler->Initial(m_spThis);
        m_spSendToOvideoCDN = shared_ptr<CSendToOVideoCDN>(new CSendToOVideoCDN(m_strStreamID, m_spEngine));
        if (!m_spSendToOvideoCDN->Initlize(m_strHost, m_strUri, bRecord))
        {
            ERROR_LOG(TAG << "Initlize live publisher handler failed.");
            break;
        }
        bRet = true;
    } while (0);

    return bRet;
}

void CLivePublisher::PushStream(const char *pData, int nLen)
{
    m_spSendToOvideoCDN->RecvRemuxStream(pData, nLen);
}

void CLivePublisher::Release()
{
    if (m_spMsgHandler != nullptr)
    {
        auto lambaDestroy = [&]() mutable
        {
            m_spSendToOvideoCDN = nullptr;
            m_spThis = nullptr;
        };
        m_spMsgHandler->ScheduleAtOnce(std::bind(lambaDestroy));
    }
    else
    {
        m_spThis = nullptr;
    }
}

void CLivePublisher::HoldMyself()
{
    Assert(m_spThis == nullptr);
    m_spThis = shared_from_this();
}
